package com.getpebble.android.core.auth.account;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.OnAccountsUpdateListener;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import com.getpebble.android.common.auth.PblSessionManager;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.core.auth.activity.LoginActivity;

public class PblAuthenticationService extends Service {
    private static final String TAG = PblAuthenticationService.class.getSimpleName();
    private final OnAccountsUpdateListener updateListener = new OnAccountsUpdateListener() {
        public void onAccountsUpdated(Account[] accounts) {
            PblSessionManager pblSessionManager = PblSessionManager.createInstance(PblAuthenticationService.this);
            if (PblSessionManager.getPebbleAccount() == null) {
                Trace.debug(PblAuthenticationService.TAG, "No longer have a pebble account");
                pblSessionManager.removeAccount();
                Intent intent = new Intent(PblAuthenticationService.this, LoginActivity.class);
                intent.addFlags(268500992);
                PblAuthenticationService.this.startActivity(intent);
            }
        }
    };

    public void onCreate() {
        super.onCreate();
        AccountManager.get(this).addOnAccountsUpdatedListener(this.updateListener, new Handler(Looper.getMainLooper()), true);
    }

    public IBinder onBind(Intent intent) {
        return new PblAccountAuthenticator(this).getIBinder();
    }

    public void onDestroy() {
        super.onDestroy();
        AccountManager.get(this).removeOnAccountsUpdatedListener(this.updateListener);
    }
}
